package com.xuzhiguang.baidu.pan.sdk.common.http;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xuzhiguang
 * @date 2020/6/25 20:41
 */
public class FormBodyRequestBuilder {

    private final Map<String, String> formData = new LinkedHashMap<>();

    private final Request request;

    public FormBodyRequestBuilder() {
        request = new Request();
        request.getHeaders().put("Content-Type", "application/x-www-from-urlencoded");
        request.setHttpMethod(HttpMethod.POST);
    }

    public FormBodyRequestBuilder url(String url) {
        request.setUrl(url);
        return this;
    }

    public FormBodyRequestBuilder httpMethod(HttpMethod httpMethod) {
        request.setHttpMethod(httpMethod);
        return this;
    }

    public FormBodyRequestBuilder addParameter(String key, String value) {
        request.getParameters().put(key, value);
        return this;
    }

    public FormBodyRequestBuilder addParameters(Map<String, String> parameters) {
        if (parameters != null) {
            request.getParameters().putAll(parameters);
        }
        return this;
    }

    public FormBodyRequestBuilder addHeader(String key, String value) {
        request.getHeaders().put(key, value);
        return this;
    }

    public FormBodyRequestBuilder addHeaders(Map<String, String> headers) {
        if (headers != null) {
            request.getHeaders().putAll(headers);
        }
        return this;
    }

    public FormBodyRequestBuilder addFormData(String key, String value) {
        formData.put(key, value);
        return this;
    }

    public FormBodyRequestBuilder addFormDatas(Map<String, String> formDatas) {
        if (formDatas != null) {
            formData.putAll(formDatas);
        }
        return this;
    }

    public Request build() {

        byte[] content;
        String str = HttpUtil.parametersToString(this.formData);
        content = str.getBytes();
        request.setContent(content);
        request.setContentLength(content.length);

        return request;
    }

}
